package binarysearch;

import java.net.SocketTimeoutException;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/22 17:21
 */
public class BinarySearchDemo3 {

    public static void main(String[] args) {

        int[] nums = {1,2,2,2,3,3,3,3,3,3,4,5,6};
        int i = bianrySearchFirst1(nums, 3);
        System.out.println(i);

    }

    //只有找到nums[mid] == target && nums[mid - 1] != target才返回target，
    //否则将right = mid - 1，再进入循环
    public static int bianrySearchFirst1(int[] nums,int target){

        int left = 0;
        int right = nums.length - 1;
        while (left <= right){

            int mid = left + (right - left) / 2;
            if(nums[mid] < target){ //target在mid的右边
                left = mid + 1;
            }else if(nums[mid] > target){ //target在mid的左边
                right = mid - 1;
            }else {
                if(mid >= 1 && nums[mid - 1] != target){
                    return mid;
                }
                right = mid - 1;
            }
        }
        return -1;
    }
}
